from datetime import datetime

from django.db import models, transaction


class EnabledUserManager(models.Manager):
    def get_queryset(self):
        return super(EnabledUserManager, self).get_queryset().filter(
            is_enabled=True)

    def create_user(self, username, **kwargs):
        """
        建立用户模型与其他相关模型

        :param username: 用户名
        :param kwargs: 其他用户模型相关的关键字参数

        """
        with transaction.atomic():
            user = self.create(username=username, **kwargs)
            user.save()
            if 'name' not in kwargs:
                user.name = '创易用户 %s' % user.id
                user.save(update_fields=['name'])
        return user


class DisabledUserManager(models.Manager):
    def get_queryset(self):
        return super(DisabledUserManager, self).get_queryset().filter(
            is_enabled=False)


class User(models.Model):
    """
    用户账户信息

    """
    username = models.CharField(
        '用户名', max_length=15, unique=True, db_index=True)
    name = models.CharField(
        '昵称', max_length=15, db_index=True)
    is_enabled = models.BooleanField(
        '是否有效', default=True)
    create_time = models.DateTimeField(
        '注册时间', default=datetime.now, db_index=True)
    update_time = models.DateTimeField(
        '更新时间', auto_now=True, db_index=True)

    objects = models.Manager()
    enabled = EnabledUserManager()
    disabled = DisabledUserManager()

    class Meta:
        db_table = 'user'

